<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">

			<div class="header">
<input type="checkbox"  :checked="allChecked"  @change="changeAll" />

			</div>

			<ul>
				<li v-for="(item,index) in list">
					<input type="checkbox" v-model="item.checked" />
					<img :src="imgPrefix + item.pro_img" width="100" height="100" alt="">

					<span>{{item.pro_name}}</span> ||
					<button @click="reduce(index)">-</button>
					<span>{{item.pro_num}}</span>
					<button @click="add(index)">+</button> ||
					<span>{{item.pro_num * item.pro_price}}</span>

				</li>
			</ul>

<hr>
<div>
	
	总价：{{totalPrice}}----   数量 {{totalNum}}
</div>

		</div>
	</body>
	<script src="vue.js"></script>
	<script>
		const {
			createApp,
			ref,
			reactive,
			computed,
			watchEffect
		} = Vue;



		let cartData = [{
				'pro_name': '产品名称2', //产品名称
				'pro_num': 3, //数量
				'pro_img': 'images/test1.jpg', //图片链接
				'pro_price': 800 //单价
			},
			{
				'pro_name': '产品名称2', //产品名称
				'pro_num': 1, //数量
				'pro_img': 'images/test2.jpg', //图片链接
				'pro_price': 800 //单价
			}
		]

		const app = createApp({

			setup() {
                  cartData = cartData.map(v=>{
					  v.checked = false 
					  return v
				  })
				let list = ref(cartData)
				const imgPrefix = 'https://www.jq22.com/demo/vuegwc202007152244/'

				function add(index) {

					if (list.value[index].pro_num >= 10) {
						alert('限购')
						return
					}
					list.value[index].pro_num++
				}

				function reduce(index) {
					if (list.value[index].pro_num <= 1) {
						alert('至少买一个')
						return
					}
					list.value[index].pro_num--

				}
				
				// let checkList = computed(function(){
				// 	 return list.value.map(v=>{
				// 		 return v.checked
				// 	 })
				// })
				
				let allChecked = ref(false)
				
				function changeAll(e){
					
				
					
					  list.value.forEach(function(v){
						  v.checked = e.target.checked; 
					  })
				}
				
				let totalPrice = ref(0)
				let totalNum = ref(0)
				
				// computed()
				
				watchEffect(function(n){
					
					// console.log(n.every(v=>v.checked))
					
					allChecked.value = list.value.every(v=>v.checked)
					 let num = 0
					 let price = 0
					list.value.forEach(v=>{
						if(v.checked){
							console.log(v.pro_num)
							num+=v.pro_num;
							price+=v.pro_num*v.pro_price
						}
					})
					
					totalNum.value=num;
					totalPrice.value= price
				})

				return {
					list,
					imgPrefix,
					add,
					reduce,
					allChecked,
					changeAll,
					totalNum,
					totalPrice
				}
			}

		})

		app.mount('#app')
	</script>
</html>